



//腐蚀膨胀操作，  3*3的卷积核
//腐蚀将黑色区域腐蚀掉，图像变细
//膨胀将黑色区域膨胀掉，图像变粗

module Erosion_or_Erode(

		input						clk,
		input						rst,
		
		
		
		input						data_en,
		output					write_en,
			
		
		
		input[7:0]				flag,    //0 腐蚀；	255 膨胀   
		
		
		input[7:0]				data_in,
		output[15:0]			erosion_out
);





wire[7:0]		martix_11;
reg[7:0]			martix_12,martix_13;
wire[7:0]		martix_21;
reg[7:0]			martix_22,martix_23;
reg[7:0]			martix_31,martix_32,martix_33;

reg delay_en1;
reg delay_en2;
reg delay_en3;



assign erosion_out = {erosion_data,erosion_data};
assign write_en  = delay_en1;  







//延时两个en周期
always@(posedge clk or negedge rst)
begin

	if(rst == 1'b0)
	begin
		delay_en1 <= 1'b0;
		delay_en2 <= 1'b0;
	end

	else	
	begin
		delay_en1 <= data_en;
		delay_en2 <= delay_en1;
		//delay_en3 <= delay_en2;
	end
end





always@(posedge clk or negedge rst)
begin
	if(rst == 1'b0)
	begin
		martix_12 <= 'd0;
		martix_13 <= 'd0;	
	end
	
	else if(data_en == 1'b1)
	begin
		martix_12 <= martix_11;
		martix_13 <= martix_12;	
	end
	else
	begin
		martix_12 <= martix_12;
		martix_13 <= martix_13;	
	end
end

always@(posedge clk or negedge rst)
begin
	if(rst == 1'b0)
	begin
		martix_22 <= 'd0;
		martix_23 <= 'd0;	
	end
	
	else if(data_en == 1'b1)
	begin
		martix_22 <= martix_21;
		martix_23 <= martix_22;	
	end
	else
	begin
		martix_22 <= martix_22;
		martix_23 <= martix_23;	
	end
end

//获取gray数据
always@(posedge clk or negedge rst)
begin
	if(rst == 1'b0)
	begin
		martix_31 <='d0;
		martix_32 <='d0;
		martix_33 <='d0;
	end
	else if(data_en == 1'b1)
	begin
		martix_31 <= data_in;
		martix_32 <= martix_31;
		martix_33 <= martix_32;
	end
	else
	begin
		martix_31 <= martix_31;
		martix_32 <= martix_32;
		martix_33 <= martix_33;
	end
end


reg[7:0] erosion_data;

always@(posedge clk or negedge rst)
begin
	if(rst == 1'b0)
		erosion_data <= 'd0;
	else if(martix_31 == flag && martix_32 == flag && martix_33 == flag && martix_21 == flag && martix_22 == flag && martix_23 == flag  && martix_11 == flag && martix_12 == flag && martix_13 == flag)
			erosion_data <= flag;
	else
		erosion_data <= 'd255 - flag;
end





Shift_RAM Shift_RAM(
	.clken(data_en),
	.clock(clk),
	.shiftin(data_in),
	.shiftout(),
	.taps0x(martix_21),
	.taps1x(martix_11));
endmodule



